<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>营销管理</el-breadcrumb-item>
      <el-breadcrumb-item>广告位置</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">

      <el-card class="box-card">
        <!--搜索框区域 @click="selectAdvertise" @click="addAdvertise"-->
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input placeholder="请输入广告名字" v-model="query">
              <el-button slot="append" icon="el-icon-search" @click="selectAdvertise"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addAdvertise">新增</el-button>
          </el-col>
        </el-row>
      </el-card>

      <el-table
          :data="tableData"
          border
          style="width: 100%">
        <el-table-column
            fixed
            prop="id"
            label="id"
        >
        </el-table-column>
        <el-table-column
            prop="name"
            label="名字"
        >
        </el-table-column>
        <el-table-column prop="sapname" label="位置">
<!--          <template slot-scope="scope">
            {{scope.row.advertisePosition.name}}
          </template>-->
        </el-table-column>

        <el-table-column prop="pic" label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.pic" width="100px"/>
          </template>
        </el-table-column>
        <el-table-column
            prop="startTime"
            label="开始时间"
        >
        </el-table-column>
        <el-table-column
            prop="endTime"
            label="结束时间"
        >
        </el-table-column>
        <el-table-column
            prop="status"
            label="上下线状态" width="65"
        >
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                @change="updateStatus(scope.row.id,scope.row.status)"
                active-value="1"
                inactive-value="0"
                active-color="#13ce66"
                inactive-color="#B6B6B6">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="clickCount"
            label="点击数"
        >
        </el-table-column>
        <el-table-column
            prop="orderCount"
            label="下单数"
        >
        </el-table-column>
        <el-table-column
            prop="url"
            label="连接地址"
        >
        </el-table-column>
        <el-table-column
            prop="note"
            label="备注"
        >
        </el-table-column>
        <el-table-column
            prop="sort"
            label="排序"
        >
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="120">
          <template slot-scope="scope"><!--@click="editUpdateCustomer(scope.row)"  @click="deleteCusById(scope.row)"-->
            <el-button type="primary" icon="el-icon-edit"  size="medium"  circle  @click="editUpdateAdver(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete"  size="medium"  circle @click="deleteAdvById(scope.row)" ></el-button>
          </template>
        </el-table-column>
      </el-table>


      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!--添加信息弹出框 -->
    <el-dialog
        title="添加广告"
        :visible.sync="editAddAdvertise"
        width="50%"
        @close="closeClear"
    >
        <span slot="footer" class="dialog-footer">
            <el-form :model="advertiseForm" :rules="EditFormAdv" ref="AdvEditForm" label-width="100px" class="demo-ruleForm">

              <el-form-item label="名字" prop="name">
                <el-input type="text" v-model="advertiseForm.name"></el-input>
              </el-form-item>

              <el-form-item label="图片" prop="pic" align="left">
              <el-upload
                  class="avatar-uploader"
                  action="http://localhost:60/marketing/upload/uploadFile"
                  :show-file-list="false"
                  :headers="importHeaders"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" width="150">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              </el-form-item>

              <el-form-item label="位置" prop="sapname" align="left">
                <el-select v-model="advertiseForm.sapname" placeholder="请选择" >
                  <el-option
                      v-for="item in sapNames"
                      :key="item.index"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="开始时间" prop="startTime" align="left">
                <el-date-picker
                    v-model="value1"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime" align="left">
                <el-date-picker
                    v-model="value2"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="备注" prop="note">
                <el-input type="text" v-model="advertiseForm.note"></el-input>
              </el-form-item>

              <el-form-item label="上下线" prop="status" align="left">
                 <template >
                    <el-radio v-model="advertiseForm.status" label="1" >上线</el-radio>
                    <el-radio v-model="advertiseForm.status" label="0">下线</el-radio>
                </template>
              </el-form-item>


            </el-form>
            <el-button @click="editAddAdvertise = false">取 消</el-button>
            <el-button type="primary" @click="confirmAddAfvertise">确 定</el-button>
        </span>
    </el-dialog>

    <!--修改信息弹出框 -->
    <el-dialog
        title="修改广告信息"
        :visible.sync="editUpdateAdvertise"
        width="50%"
        @close="closeClear"
    >
        <span slot="footer" class="dialog-footer">
            <el-form :model="updateAdvertiseForm" :rules="EditFormAdv" ref="advUpdateEditForm" label-width="100px" class="demo-ruleForm">

              <el-form-item label="名字" prop="name">
                <el-input type="text" v-model="updateAdvertiseForm.name"></el-input>
              </el-form-item>

              <el-form-item label="图片" prop="pic" align="left"><!---->
                <el-upload
                    class="avatar-uploader"
                    action="http://localhost:60/marketing/upload/uploadFile"
                    :show-file-list="false"
                    :headers="importHeaders"
                    :on-success="handleAvatarSuccess1"
                    :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrlUpdate" :src="imageUrlUpdate" class="avatar" width="150">
                  <i v-else class="el-icon-plus avatar-uploader-icon">修改图片</i>
                </el-upload>

              </el-form-item>

              <el-form-item label="位置" prop="sapname" align="left">
                <el-select v-model="updateAdvertiseForm.sapname" placeholder="请选择" >
                  <el-option
                      v-for="item in sapNames"
                      :key="item.index"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="开始时间" prop="startTime" align="left">
                <el-date-picker
                    v-model="value1"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime" align="left">
                <el-date-picker
                    v-model="value2"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="备注" prop="note">
                <el-input type="text" v-model="updateAdvertiseForm.note"></el-input>
              </el-form-item>



            </el-form><!---->
            <el-button @click="editUpdateAdvertise = false">取 消</el-button>
            <el-button type="primary" @click="confirmUpdateAfvertise">确 定</el-button>
        </span>
    </el-dialog>
  </div>

</template>

<script>
var mytoken = sessionStorage.getItem('token')//要保证取到
export default {
  name: "Advertise",
  data(){
    return{
      editAddAdvertise:false, //是否打开添加弹窗
      editUpdateAdvertise:false,//是否打开修改弹出框
      advertiseForm:{}, //添加表单数据
      updateAdvertiseForm:{},//修改表单数据
      query:"", //查询条件
      currentPage: 1, //当前页码
      pageSize:5, //每页显示几条
      total:0,  //总条数
      tableData:[],
      sapNames:[],
      value1:"",
      value2:"",
      importHeaders:{token: mytoken},
      imageUrl: '',//上传图片路径
      imageUrlUpdate:'',//修改图片路径
      //信息校验
      EditFormAdv: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
        ],
       /* pic: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ],*/
        sapname: [
          { required: true, message: '位置不能为空', trigger: 'change' }
        ],
        /*startTime:[
          { required: true, message: '开始时间不能为空', trigger: 'change' }
        ],
        endTime:[
          { required: true, message: '结束时间不能为空', trigger: 'change' }
        ],*/
        note:[
          { required: true, message: '备注不能为空', trigger: 'blur' }
        ],

      }
    }
  },
  //页面加载完毕后执行的方法
  created() {
    this.initadvertable(this.currentPage,this.pageSize);
  },
  methods:{
    closeClear(){
      this.$refs.AdvEditForm.resetFields();
      this.$refs.advUpdateEditForm.resetFields();
      this.initadvertable(this.currentPage,this.pageSize);
    },
    //展示广告管理信息
    initadvertable(currentPage,pageSize){
      var that = this;
      this.$http.post(`/marketing/tbAdvertise/findAdvertiseByPage/${currentPage}/${pageSize}?query=${this.query}`).then(function (resp){
        if (resp.data.code==200){
          that.tableData = resp.data.data.records;
          that.total = resp.data.data.total;
        }else {
          that.$message.error("用户加载失败")
        }
      })
    },
    //切换每页显示的条数
    handleSizeChange(val) {
      this.pageSize=val;
      this.initadvertable(this.currentPage,this.pageSize);
    },
    //切换当前页码
    handleCurrentChange(val) {
      this.currentPage=val;
      this.initadvertable(this.currentPage,this.pageSize)
    },
    //搜索
    selectAdvertise(val){
      this.initadvertable(this.currentPage,this.pageSize)
    },
    //修改状态
    updateStatus(id,status){
      var that = this;
      this.$http.put(`/marketing/tbAdvertise/updateStatus/${id}/${status}`,).then(function (resp){
        if (resp.data.code==200){
          that.$message.success(resp.data.msg);
        }else {
          that.$message.error(resp.data.msg)
        }
        that.initadvertable(that.currentPage,that.pageSize);
      })
    },
    //打开添加弹出框
    addAdvertise(){
      this.advertiseForm={}; //清空数据
      this.value1=""
      this.value2=""
      this.editAddAdvertise=true;
      this.advertiseForm.status="0"
      this.imageUrl="";
      var  that=this
      //填充下拉框
      this.$http.get(`/marketing/tbAdvertisePosition/findAllAdvertisePosition`).then(function (resp){
        if (resp.data.code===200){
          that.sapNames=resp.data.data
        }
      })
    },
    //上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = res;//地址复制给imageUrl
    },
    //修改图片路径
    handleAvatarSuccess1(res, file) {
      this.imageUrlUpdate = res;//地址复制给imageUrl
    },

    //上传前校验图片
    beforeAvatarUpload(file) {
      //const isJPG = file.type === 'image/jpeg';isJPG &&
      const isLt2M = file.size / 1024 / 1024 < 2;

      /*if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }*/
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return  isLt2M;
    },

    //确认添加
    confirmAddAfvertise(){
      this.advertiseForm.startTime=this.value1;
      this.advertiseForm.endTime=this.value2;
      this.advertiseForm.pic=this.imageUrl;
      var that = this;
      this.$refs[`AdvEditForm`].validate((valid) =>{
        if (valid){
          this.$http.post("/marketing/tbAdvertise/addAdvertise",this.advertiseForm).then(function (resp){
             console.log(resp)
            if (resp.data.code===200){
              that.editAddAdvertise=false;
              that.$message.success("添加成功")
              that.initadvertable(that.currentPage,that.pageSize);
            }else {
              that.$message.error(resp.data.msg)
            }
          })
        }
      })
    },
    //打开修改弹出框
    editUpdateAdver(row){
      //this.updateAdvertiseForm={}; //清空数据
      this.editUpdateAdvertise=true;
      this.updateAdvertiseForm=row;
      this.imageUrlUpdate=row.pic;
      this.value1=row.startTime;
      this.value2=row.endTime;
      var that=this
      //填充下拉框
      this.$http.get(`/marketing/tbAdvertisePosition/findAllAdvertisePosition`).then(function (resp){
        if (resp.data.code===200){
          that.sapNames=resp.data.data
        }
      })
    },
    //确认修改
    confirmUpdateAfvertise() {
      this.updateAdvertiseForm.startTime = this.value1;
      this.updateAdvertiseForm.endTime = this.value2;
      this.updateAdvertiseForm.pic = this.imageUrlUpdate;
      var that = this;
      this.$refs[`advUpdateEditForm`].validate((valid) => {
        if (valid) {
          this.$http.post("/marketing/tbAdvertise/updateAdvertise", this.updateAdvertiseForm).then(function (resp) {
            if (resp.data.code === 200) {
              that.editUpdateAdvertise = false;
              that.$message.success("添加成功")
              that.initadvertable(that.currentPage, that.pageSize);
            } else {
              that.$message.error(resp.data.msg)
            }
          })
        }
      })
    },
//删除
    deleteAdvById(row){
      var that = this;
      this.$confirm('是否删除','提示',{
        confirmButtonText:'确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        that.$http.post(`/marketing/tbAdvertise/deleteAdvertise/${row.id}`).then(function (resp){
          if (resp.data.code == 200){
            that.$message.success(resp.data.msg)
            that.initadvertable(that.currentPage,that.pageSize);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
  },
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>